package com.huluobo.a2110mvpimdemo.pay;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.hardware.biometrics.BiometricPrompt;
import android.os.Build;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.huluobo.a2110mvpimdemo.R;
import com.huluobo.a2110mvpimdemo.pay.util.OrderInfoUtil2_0;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;


import java.util.Map;

public class PayActivity extends AppCompatActivity {

    private EditText payEt;
    private Button toPay;
    private TextView title;
    private ImageView back;

    private String username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        username = getIntent().getStringExtra("conversationId");

        title = findViewById(R.id.header_title);
        back = findViewById(R.id.header_back);
        title.setText("发送红包给" + username);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(v -> {
            finish();
        });


        payEt = findViewById(R.id.pay_price);
        toPay = findViewById(R.id.pay_toPay);


        toPay.setOnClickListener(v -> {
            if (Integer.parseInt(payEt.getText().toString()) <= 200) {
                pointPay();
            } else {
                Toast.makeText(this, "红包金额不支持大于200", Toast.LENGTH_SHORT).show();
            }

        });

        //指纹识别初始化
        //需要api大于29才有传感器
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            biometricPrompt = new BiometricPrompt.Builder(this)
                    .setTitle("红包支付")
                    .setNegativeButton("取消", getMainExecutor(), (dialog, which) -> {
                        Toast.makeText(this, "取消支付", Toast.LENGTH_SHORT).show();
                    })
                    .build();
        }

        cancellationSignal = new CancellationSignal();
        cancellationSignal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
            @Override
            public void onCancel() {
                Toast.makeText(PayActivity.this, "取消支付", Toast.LENGTH_SHORT).show();
            }
        });
    }

    //指纹支付
    public void pointPay() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            biometricPrompt.authenticate(cancellationSignal, getMainExecutor(),
                    new BiometricPrompt.AuthenticationCallback() {
                @Override
                public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
                    super.onAuthenticationSucceeded(result);
                    pay();
                }
            });
        }
    }

    /**
     * 支付宝相关
     */
    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    public static final String APPID =
            "2016103000779553";

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    public static final String PID = "";

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    public static final String TARGET_ID = "";
    /**
     * pkcs8 格式的商户私钥。
     * <p>
     * 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * RSA2_PRIVATE。
     * <p>
     * 建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCYJYflUySpQ" +
            "//IL3wxdS937UV3iUw2VFXSYfq60DjS3/m73nM23uddswvuRoO+822JuekiXbfvkmGWYXNdXKqAoempPIl" +
            "+ADxEXqvYGioyMLqVqV1meVQkGfVSr" +
            "+CxQ9rkmdkVaKWqqDrVeFcUlN9ceW8YLJiKhpBT6hhqFPh7pngLIm6EotQ3mMNZoRID4yXpu8p6Eo8468Xr7mQZhfqGkjnXUWlhewBItZWdQ9JcwEsWsRUtCmk/BbAO+H7NrVv2oWREIacoKD0Ws79cAmdhQwsDFjnC/5qkb9hZj1ahhlS2zzEp6rhxERiI63+ee6sRO/pPJoaTTBUST0kpUcL5AgMBAAECgg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lQwda4/GrUyllUWf7akTSLkT+VvkfbcHaHB2Vil8LFYt/SKteKPBy7l0YRuNq74FLZka6Y6OmmemHXRSqOJzcEGyrOWT5ElLmywMltQK4s0VXwTAtsForDE4eqmuz1rZ0Er4rsKdVpdu/I5A=";

    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        ToastUtils.showShort("支付成功");
                        Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        ToastUtils.showShort("支付失败" + payResult);
                        Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        EMMessage emMessage = EMMessage.createTextSendMessage("发送了一个" + payEt.getText().toString() +
                                        "红包",
                                username);
                        EMClient.getInstance().chatManager().sendMessage(emMessage);
                        finish();
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };

    /**
     * 支付宝支付业务示例
     */
    public void pay() {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            return;
        }

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo 的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        final Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    /**
     * 指纹相关
     */
    //生物识别传感器
    private BiometricPrompt biometricPrompt;
    //取消签名
    private CancellationSignal cancellationSignal;
}